package org.jackysoft.spring;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.core.Ordered;

public class ActionBeanPostProcessor implements BeanPostProcessor, Ordered,
		BeanFactoryPostProcessor {

	private static final Log logger = LogFactory
			.getLog(ActionBeanPostProcessor.class);

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName)
			throws BeansException {

		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName)
			throws BeansException {
		boolean action = bean instanceof org.jackysoft.struts2.AbstractAction;
		if (!action)
			return bean;
		String[] names = { "bean" };

		try {
			Field[] fields = bean.getClass().getDeclaredFields();
			Field field = null;
			out: for (Field f : fields) {
				for (String name : names) {
					if (name.equals(f.getName())) {
						field = f;
						break out;
					}
				}
			}

			if (field == null) {
				for (String name : names) {
					field = bean.getClass().getDeclaredField(name);
					if (field != null) {
						break;
					}
				}
			}

			if (field == null) {
				for (String name : names) {
					field = bean.getClass().getField(name);
					if (field != null) {
						break;
					}
				}
			}

			if (field == null) {
				logger.warn("Action :" + bean.getClass().getName()
						+ " has no property  bean");
				return bean;
			}
			Class<?> beanType = field.getType();
			PropertyUtils.setProperty(bean, "type", beanType);
			
			
		} catch (SecurityException e) {
			logger.warn(e);
		} catch (NoSuchFieldException e) {
			logger.warn("Action property " + bean.getClass().getName()
					+ " not found  with :" + e.getMessage());

		} catch (IllegalAccessException e) {
			logger.info(e);
		} catch (InvocationTargetException e) {
			logger.info(e);
		} catch (NoSuchMethodException e) {
			logger.warn("Action property " + bean.getClass().getName()
					+ " not found  with :" + e.getMessage());

		}

		return bean;
	}

	@Override
	public int getOrder() {
		return 0;
	}

	@Override
	public void postProcessBeanFactory(
			ConfigurableListableBeanFactory beanFactory) throws BeansException {

	}

}
